<?php

/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class AppModel extends Model 
{
    /**
     * Define $actsAs
     *
     */
    var $actsAs = array('Containable','SoftDeletable');

    /**
     * Describe checkUnique
     *
     * @param $data
     * @param $fieldName
     * @return null 
     */
    function checkUnique($data, $fieldName) {
        $valid = false;
        if(isset($fieldName) && $this->hasField($fieldName))
        {
            $valid = $this->isUnique(array($fieldName => $data));
        }
        return $valid;
    } 

    /**
     * Describe getData
     *
     * @param $fields
     * @param $conditions
     * @return null
     */
    function getData($fields=array(),$conditions=array()){
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $queryData = array(
            'conditions'   => $conditions,
            'fields'       => $fields,
        );
        $data = $db->read($this, $queryData, false);
        return $data;
    }

    /**
     * Returns a resultset array with DISTINCT fields from database matching given conditions.
     *
     * @param   mixed    $conditions SQL conditions as a string or as an array('field' =>'value',...)
     * @param   mixed    $fields Either a single string of a field name, or an array of field names
     * @return  array    Array of records
     */
    /**
     * Describe findDistinct
     *
     * @param $conditions
     * @param $fields
     * @return null
     */
    function findDistinct($conditions = null, $fields = null)
    {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $order='';

        $str = 'DISTINCT ';
        if (!is_array($fields))
        {
            $str .= '`' . $fields . '`';
            $order=$fields;
        }
        else
        {
            foreach ($fields as $field)
            {
                $str .= '`' . $field . '`, ';
            }
            $str = substr($str, 0, -2);
        }
        $queryData = array(
            'conditions'   => $conditions,
            'fields'       => $str,
            'order'        => $order
        );
        $data = $db->read($this, $queryData, false);
        return $data;
    }

    /**
     *
     * Replace path in template with data from array
     *
     * @param string $template Template with all the placeholders to be replaced
     * @param array  $data     Data to be replaced in the template
     * @return string Template with all the placeholders replaced with whatever data available in array
     *
     */

    function replacetemplate($template,$data=null){
        preg_match_all('/(%[a-zA-Z._:]+)/',$template,$matches);
        foreach($matches[1] as $curmatch){
            $curmatch=substr($curmatch,1);
            // remove trailing . 
            if(substr($curmatch,-1,1)=='.' && Set::check($data,substr($curmatch,0,-1))){
                $curmatch=substr($curmatch,0,-1);
            }
            $fullmatch=$curmatch;
            // get the text to link to
            if(($pos=strpos($curmatch,':'))!==false){
                $text=substr($curmatch,$pos+1);
                $curmatch=substr($curmatch,0,$pos);
            }
            else{
                $text='address';
            }
            if(Set::check($data,$curmatch)){ 
                $replacedata=Set::classicExtract($data,$curmatch);
                if($curmatch=='Meeting.meeting_date' || $curmatch=='OldMeeting.meeting_date'){
                    $ddate=strtotime($replacedata);
                    $replacedata=sprintf(__('%s,%s',true),date(Configure::read('date_format'),$ddate),date(Configure::read('time_format'),$ddate));
                }
                elseif(strtolower(substr($curmatch,0,4))=='link'){ // if it's %Link.aaa:bbbb
                    $server=Configure::read('server_url');
                    if(($pos=strpos($server,'://'))!==false){
                        $protocol=substr($server,0,$pos).'://';
                    }elseif(isset($_SERVER["HTTPS"])){
                        $protocol='https://';
                    }else{
                        $protocol='http://';
                    }
                    if(isset($_SERVER['SERVER_NAME'])){
                        $server=$_SERVER['SERVER_NAME'];
                    }
                    $address=$protocol.$server.Router::url($replacedata);
                    if($text=='address') $text=$address;
                    $replacedata="<a href='$address'>$text</a>";
                }
                $template=str_replace('%'.$fullmatch,$replacedata,$template);
            }
        }
        return $template;
    }
    
    function afterSave($created) {
        if ($this->name != 'Log' && isset($this->curUser)) { //skip Log model
            if ($created)
                $this->log("[".get_class($this)." ".__FUNCTION__." ".$this->curUser."] ".$this->getInsertID()." created", LOG_DEBUG);
            else
                $this->log("[".get_class($this)." ".__FUNCTION__." ".$this->curUser."] ".$this->getID()." edited", LOG_DEBUG);
        }
    }
}
?>
